import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

//pdf-content00 PDF块级id
//pdf-item00  PDF块级部分class

const htmlToPdf = (id, title, fileName) => {
    const A4_WIDTH = 592.28;
    const A4_HEIGHT = 811.89;
    let target = document.getElementById(id);
    let _title;
    _title = document.createElement("div");
    _title.id = "pdf-item-id";
    _title.innerHTML = title;
    _title.style =
        "font-size: 24px;font-weight: 600; color: #000; margin: 20px 0;text-align: center;";
    target.insertBefore(_title, target.children[0]);
    let pageHeight = (target.scrollWidth / A4_WIDTH) * A4_HEIGHT;
    // 获取分割dom，此处为class类名为item的dom
    let lableListID = document.getElementsByClassName("pdf-item00");
    // 进行分割操作，当dom内容已超出a4的高度，则将该dom前插入一个空dom，把他挤下去，分割
    for (let i = 0; i < lableListID.length; i++) {
        let multiple = Math.ceil(
            (lableListID[i].offsetTop + lableListID[i].offsetHeight) /
                pageHeight
        );
        if (isSplit(lableListID, i, multiple * pageHeight)) {
            let divParent = lableListID[i].parentNode; // 获取该div的父节点
            let newNode = document.createElement("div");
            newNode.className = "emptyDiv";
            newNode.style.background = "#ffffff";
            let _H =
                multiple * pageHeight -
                (lableListID[i].offsetTop + lableListID[i].offsetHeight + 80);
            newNode.style.height = _H + 140 + "px"; 

            newNode.style.width = "100%";
            let next = lableListID[i].nextSibling; // 获取div的下一个兄弟节点
            
            // 判断兄弟节点是否存在
            if (next) {
                // 存在则将新节点插入到div的下一个兄弟节点之前，即div之后
                divParent.insertBefore(newNode, next);
            } else {
                // 不存在则直接添加到最后,appendChild默认添加到divParent的最后
                divParent.appendChild(newNode);
            }
        }
    }
    getPdf(id, fileName);
};

const getPdf = (dom, title) => {
    let _dom = document.getElementById(dom);
    var width = _dom.offsetWidth;
    var heigth = _dom.offsetHeight;

    var _canvas = document.createElement("canvas");
    var scale = 2;
    _canvas.width = width * scale;
    _canvas.height = heigth * scale;
    _canvas.getContext("2d").scale(1, 1);

    var opts = {
        scale,
        canvas: _canvas,
        useCORS: true,
        allowTaint: true,
    };

    return new Promise((resolve, reject) => {
        html2Canvas(_dom, opts)
            .then(function (canvas) {
                let contentWidth = canvas.width;
                let contentHeight = canvas.height;
                // 根据A4纸的大小，计算出dom相应比例的尺寸
                let pageHeight = (contentWidth / 592.28) * 841.89;
                let leftHeight = contentHeight;
                let position = 0;
                let imgWidth = 595.28;
                // 根据a4比例计算出需要分割的实际dom位置
                let imgHeight = (592.28 / contentWidth) * contentHeight;
                // canvas绘图生成image数据，1.0是质量参数
                let pageData = canvas.toDataURL("image/jpeg", 1.0);
                // a4大小
                let PDF = new JsPDF("", "pt", "a4");
                // 当内容达到a4纸的高度时，分割，将一整块画幅分割出一页页的a4大小，导出pdf
                if (leftHeight < pageHeight) {
                    PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
                } else {
                    while (leftHeight > 0) {
                        PDF.addImage(
                            pageData,
                            "JPEG",
                            0,
                            position,
                            imgWidth,
                            imgHeight
                        );
                        leftHeight -= pageHeight;
                        position -= 841.89;
                        if (leftHeight > 0) {
                            PDF.addPage();
                        }
                    }
                }
                // 导出
                PDF.save(title + ".pdf");
                //删除调价的标题
                let _title = document.getElementById("pdf-item-id");
                _title && _dom.removeChild(_title);
                let _pdfDom = document.getElementById("pdf-content00");
                let emptyDiv =
                    document.getElementsByClassName("emptyDiv") || [];
                
                console.log(emptyDiv.length)
                //删除空白元素
                for (let i = 0; i < emptyDiv.length; i++) {
                    _pdfDom.removeChild(emptyDiv[i]);
                }
                resolve(true);
            })
            .catch((err) => {
                console.log(err);
                reject(false);
            });
    });
};

const isSplit = (nodes, index, pageHeight) => {
    // 计算当前这块dom是否跨越了a4大小，以此分割
    if (
        nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight &&
        nodes[index + 1] &&
        nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight
    ) {
        return true;
    }
    return false;
};

export default htmlToPdf;
